package ltd.followkba.comment;

import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URLEncoder;
import java.util.Random;

import ltd.followkba.comment.bean.BSongInfo;
import ltd.followkba.comment.bean.BTaskRun;
import ltd.followkba.comment.bean.BUserInfo;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;

public class TransChangBa extends KgChangBa {
    @Override
    public String uploadPhotoFile(String remFile, String locPhotoFile, BTaskRun bTaskRun){
        String gsLocal_1 = MUTIL.GET_RANDOM_ID_STRING();
        String gsLocal_2 = "";
        if ("".equals(gsUserID)){
            return "error：没有设置用户ID";
        }
        int g4Local_1 = 0;
        if (!"".equals(remFile)) {
            locPhotoFile = gsWorkPath + "upload.jpg";//gsLocal_1.substring(0, 7) + ".jpg";
            do {
                if (MUTIL.GET_URL_TO_FILE(remFile, locPhotoFile) > 0) {
                    break;
                }
            } while (++g4Local_1 < 5);
        }
        String upPhotoFile = gsLocal_1 + "crop_photo.jpg";
        MSTRING("uploadPhotoFile A "+ locPhotoFile+" "+ MAPI.GET_FILE_LENGTH(locPhotoFile)+" "+upPhotoFile);
        gsLocal_1 = "http://upimgapi.changba.com/ktvbox.php?ac=uploaduserheadphoto&bless=1&channelsrc=market_%E8%85%BE%E8%AE%AF&macaddress=" + mDeviceMac;
        gsLocal_1 += "&deviceid=" + mDeviceMac + "&version=8.6.2";
//MLOG(gsLocal_1);MLOG(mChangBa.mUserID);MLOG(mChangBa.mToken);
        OkHttpClient mOkHttpClient = new OkHttpClient();
        File file = new File(locPhotoFile);
        Response response = null;
        g4Local_1 = 0;
        do {
            try {
                RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                RequestBody requestBody = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"userid\""), RequestBody.create(null, gsUserID))
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"curuserid\""), RequestBody.create(null, gsUserID))
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"token\""), RequestBody.create(null, gsToken))
                        .addPart(Headers.of("Content-Disposition", "form-data; name=\"imgdata\";filename=\"" + upPhotoFile + "\""), fileBody)
                        .build();
                Request request = new Request.Builder()
                        .url(gsLocal_1 + MUTIL.GET_SERET_USER_INFO(gsLocal_1))
                        .header("User-Agent", mUserAgent)
                        .post(requestBody)
                        .build();
                response = mOkHttpClient.newCall(request).execute();
                gsLocal_2 = response.body().string();
                MSTRING("uploadPhotoFile C "+gsLocal_2);
                if (response.code() < 200 || response.code() > 201) {
                }
                else {
                    gsLocal_2 = MUTIL.GET_JSON_STRING(gsLocal_2, "errorcode");
                    MSTRING("uploadPhotoFile D "+gsLocal_2);
                    if ("ok".equals(gsLocal_2)) {
                        //         MAPI.DELETE_FILE(locPhotoFile);
                        return "ok";
                    }
                }
            } catch (IOException e) {
            }
            MAPI.MSLEEP(1000);
        } while (++g4Local_1 < 5);
        return "error";
    }
     @Override
    public String copyMediaFile(int video, int number, BUserInfo copyUserInfo, BTaskRun bTaskRun, String intro) {
//copyUserInfo=mChangBa.GetUserFullInfo(0, "78441656");
      if (copyUserInfo.songQty < 1) {
            return "error:用户没有歌曲";
        }
        if (copyUserInfo.songQty > copyUserInfo.songIDs.size()){
            copyUserInfo.songQty = copyUserInfo.songIDs.size();
        }

        ResultNet resultNet;
        int g4Local_1 = copyUserInfo.songQty - 1;
        if (number != -1) {
            g4Local_1 = number;
        }
//g4Local_1=0;MLOG(g4Local_1);MLOG(copyUserInfo.WorksQty);MLOG(copyUserInfo.IdS.get(g4Local_1));

        BSongInfo aSongInfo = GetSongInfo(copyUserInfo.songIDs.get(g4Local_1));
        if (aSongInfo == null){
            return "error:读取歌曲信息出错(" + copyUserInfo.nickName + ")";
        }
        if (!"".equals(intro)){
            aSongInfo.intro = intro;
        }else {
            if (aSongInfo.intro.length() < bTaskRun.mBAccount.UploadIntroWord) {
        //             aSongInfo.Intro = MUTIL.GET_AUTO_INTRO();
                aSongInfo.intro = MKCS.GetBingSongIntro(true);
            }
        }
//MLOG(aSongInfo.WorksName);MLOG(aSongInfo.Intro);MLOG(aSongInfo.AudioUrl);MLOG(aSongInfo.IdS);
        String gsLocal_1 = String.format("唱吧复制 %s，歌曲%d(%s) %s %s", copyUserInfo.nickName, g4Local_1, aSongInfo.songName, aSongInfo.musicID, aSongInfo.path);
        bTaskRun.UploadResult = gsLocal_1;
        gsLocal_1 = "&songid=" + aSongInfo.musicID + "&music_gain=-3&sinaAt=&shareFlag=sina_&voice_gain=0&shareContent=" + URLEncoder.encode(aSongInfo.intro);
        gsLocal_1 += "&content=" + URLEncoder.encode(aSongInfo.intro) + "&songname=" + URLEncoder.encode(aSongInfo.songName);
//        gsLocal_1 += "&area=" + URLEncoder.encode(copyUserInfo.Province) + "&effect=13";
gsLocal_1 += "&area=%E5%8C%97%E4%BA%AC&effect=13";


        g4Local_1 = 0;
         String SongPath = aSongInfo.videoPath;
         if ("0".equals(aSongInfo.isMV)){
             video = 0;
         }
         if (video == 0) {
             SongPath = aSongInfo.path;
         }
         String gsLocal_2 = "error";
         do {
             gsLocal_2 = uploadMediaFile(video, SongPath, gsLocal_1, bTaskRun);
             if ("ok".equals(gsLocal_2)){
                 return "ok";
             }
             else {
                 MSTRING("上传出错："+g4Local_1+" "+gsLocal_2);
             }
             MAPI.MSLEEP(20);
         } while (++g4Local_1 < 5);
        return gsLocal_2;
    }
    public String uploadMediaFile(int video, String mediaFileUrl, String setting, BTaskRun bTaskRun) {
        String gsLocal_1;
        String gsLocal_2;
        String gsLocal_3;
        String gsLocal_4;
        String gsLocal_5;
        String gsLocal_6;
        String locMediaFile;
        if (video == 0) {
            locMediaFile = gsWorkPath + "upload.mp3";
            gsLocal_1 = "http://upworkapi.changba.com/ktvbox.php?ac=uploaduserworkwithqiniu_updatedb";
            bTaskRun.UploadResult = "上传MP3 " + mediaFileUrl;
        }
        else {
            locMediaFile = gsWorkPath + "upload.mp4";
            gsLocal_1 = "http://upworkapi.changba.com/ktvbox.php?ac=uploaduserworkwithqiniu_videodb";
            bTaskRun.UploadResult = "上传MP4 " + mediaFileUrl;
        }
        gsLocal_1 += "&bless=1&channelsrc=market_%E8%85%BE%E8%AE%AF&macaddress=" + mDeviceMac + "&deviceid=" + mDeviceMac + "&version=8.6.2";
        gsLocal_2 = "tags=&curuserid=" + gsUserID + "&qqAt=" + setting + "&token=" + gsToken +"&isprivate=0&device=GT-N7102&duetid=0&longitude=" + gsLongitude;
        gsLocal_2 += "&dpi=0&latitude=" + gsLatitude + "&offset=0&earphone=1&eq=0&";
        if (MUTIL.GET_URL_TO_FILE(mediaFileUrl, locMediaFile) < 1) {
            return "error：无法下载" + mediaFileUrl;
        }
        bTaskRun.UploadResult = "准备上传MP3 ";
        MAPI.MSLEEP(1000);

        ResultNet resultNet = new ResultNet();
        gsLocal_3 = WriteToSvr(gsLocal_1, gsLocal_2);
        bTaskRun.UploadResult = "uploadMediaFile "+gsLocal_1;
        if (MakeStdReturn(gsLocal_3, resultNet) == true) {
            gsLocal_1 = MUTIL.GET_JSON_STRING(resultNet.nextJason, "signature");
            int gReturnStep=0;
            gsLocal_2 = "UpToken " + gsLocal_1;
            gsLocal_1 = "http://upload.qiniu.com";
            RandomAccessFile gfLocal_1 = null;
            byte[] gpLocal_1 = new byte[262144];
            int g4Local_1 = (int) MAPI.GET_FILE_LENGTH(locMediaFile);
            int g4Local_2;
            int g4Local_3;
            int g4Local_4;
            int g4Local_5 = g4Local_1;
            byte gLocal_1 = 0;
            g4Local_2 = 0;
            gsLocal_5 = "";
            gsLocal_6 = "";
            try {
                gfLocal_1 = new RandomAccessFile(locMediaFile, "r");
                do {
                    if (g4Local_1 > 4194304){
                        g4Local_3 = 4194304;
                        g4Local_1 -= 4194304;
                    }
                    else {
                        g4Local_3 = g4Local_1;
                        g4Local_1 = 0;
                    }
                    gsLocal_3 = String.format("/mkblk/%d", g4Local_3);
                    do {
                        if (g4Local_3 > 262144){
                            g4Local_4 = 262144;
                            g4Local_3 -= 262144;
                        }
                        else {
                            g4Local_4 = g4Local_3;
                            g4Local_3 = 0;
                        }
                        gfLocal_1.read(gpLocal_1, 0, g4Local_4);
                        gsLocal_4 = qiniu_com_block(gsLocal_1 + gsLocal_3, gsLocal_2, g4Local_4, gpLocal_1);
                       MSTRING(gsLocal_4);
                        if ("".equals(gsLocal_4)){
                            returnBusyMessage(50, 100, "upload.qiniu.com没有返回");
                            break;
                        }
                        gsLocal_6 = MUTIL.GET_JSON_STRING(gsLocal_4, "ctx");
                        if ("".equals(gsLocal_6)){
                            returnBusyMessage(60, 100, "upload.qiniu.com返回出错");
                            break;
                        }
                        gsLocal_3 = MUTIL.GET_JSON_STRING(gsLocal_4, "offset");
                        gsLocal_3 = "/bput/" + gsLocal_6 + "/" + gsLocal_3;
                        g4Local_2 += g4Local_4;
                        bTaskRun.UploadResult = "上传：" + MUTIL.GET_PERCENT_COUNT(g4Local_2, g4Local_5) + "%";
                    } while (g4Local_3 > 0);
                    if (gLocal_1 > 0){
                        gsLocal_5 += ",";
                    }
                    gLocal_1 = 1;
                    gsLocal_5 += gsLocal_6;
                } while (g4Local_1 > 0);
                MSTRING("返回返回 "+g4Local_2 +" "+ g4Local_5);
                if (g4Local_2 == g4Local_5){
                    returnBusyMessage(100, 0, "");
                    gsLocal_3 = String.format("/mkfile/%d/mimeType/YXBwbGljYXRpb24vb2N0ZXQtc3RyZWFt/fname/cmVjb3JkXzEubXA0", g4Local_2);
                    gsLocal_4 = qiniu_com_block(gsLocal_1 + gsLocal_3, gsLocal_2, gsLocal_5.length(), gsLocal_5.getBytes());
//MDWORD(0xc3);MLOG(gsLocal_4);
                    if (video == 0) {
                        gsLocal_3 = MUTIL.GET_JSON_STRING(gsLocal_4, "result");
                        if ("ok".equals(gsLocal_3)) {
                            returnBusyMessage(100, 100, "");
                            gfLocal_1.close();
                            return "ok";
                        } else {
                            returnBusyMessage(gReturnStep, 100, "返回确认出错：" + gsLocal_4);
                        }
                    }
                    else {
                        gsLocal_3 = MUTIL.GET_JSON_STRING(gsLocal_4, "hash");
                        if (!"".equals(gsLocal_3)) {
                            returnBusyMessage(100, 100, "");
                            gfLocal_1.close();
                            return "ok";
                        } else {
                            returnBusyMessage(gReturnStep, 100, "返回确认出错：" + gsLocal_4);
                        }
                    }
                }
                else {
                    returnBusyMessage(gReturnStep, 100, "上传的文件不完整");
                }
                gfLocal_1.close();
            } catch (IOException e) {
                returnBusyMessage(gReturnStep, 100, "mp4文件出错");
            }
            return "error" + gsLocal_3;
        }
//MLOG("recruitinginfo "+MUTIL.GET_JSON_STRING(gsLocal_1, "recruitinginfo"));
        return resultNet.message;
    }
    public String WriteToSvr(String destUrl, String param) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Response response = null;
        String gsLocal_1 = "";
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8"), param);
            Request request = new Request.Builder()
                    .url(destUrl + MUTIL.GET_SERET_USER_INFO(destUrl))
                    .header("Cb-X-Seqid", "t=0;n=23;d=0")
                    .header("User-Agent", mUserAgent)
                    .post(requestBody)
                    .build();
            response = mOkHttpClient.newCall(request).execute();
            gsLocal_1 = response.body().string();
//MLOG(response.code());MLOG(gsLocal_1);
            if (response.code() != 200) {
                return "error";
            }
        } catch (IOException e) {
        }
        return gsLocal_1;
    }
    public String qiniu_com_block(String destUrl, String Authorization, int length, byte[]in_data) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Response response = null;
        String gsLocal_1 = "";
//MLOG("qiniu_com_block "+destUrl);
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8"), in_data, 0, length);
            Request request = new Request.Builder()
                    .url(destUrl)
                    .header("Authorization", Authorization)
                    .header("User-Agent", mUserAgent)
                    .post(requestBody)
                    .build();
            response = mOkHttpClient.newCall(request).execute();
            gsLocal_1 = response.body().string();
//MLOG("qiniu_com_block "+response.code());MLOG(gsLocal_1);
            if (response.code() != 200) {
                return "error";
            }
        } catch (IOException e) {
        }
        return gsLocal_1;
    }
    public void returnBusyMessage(int step, int busy, String message){
        MSTRING(step + " " + busy + " " + message);
    }


    public void DELAY_RANDOM_SECOND(int second) {
        second = second * 1000;
        Random random = new Random();
        int g4Random = Math.abs(random.nextInt()) % second;
        MAPI.MSLEEP((second / 2) + g4Random);
    }

}
